package com.java1234.servlet;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author : 章仕烜
 * @create : 2019/12/21
 **/
public class LoginServlet
        extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        super.doGet(req, resp);
        System.err.println("login doGet");
        // 请求转发到login.jsp
        req.getRequestDispatcher("login.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.err.println("login doPost");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        try {
            subject.login(token);
            Session session = subject.getSession();
            System.err.println("sessionId:" + session.getId());
            System.err.println("sessionHost:" + session.getHost());
            System.err.println("sessionTimeout:" + session.getTimeout());
            session.setAttribute("info","美国五角大楼机密数据");
            resp.sendRedirect("success.jsp");
        } catch (AuthenticationException e) {
            e.printStackTrace();
            req.setAttribute("errorInfo","用户名或密码错误!");
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        }
    }
}
